package com.example.springbootshiro.shiro.realm;

import com.example.springbootshiro.model.Permission;
import com.example.springbootshiro.model.Role;
import com.example.springbootshiro.model.User;
import com.example.springbootshiro.service.UserService;
import com.example.springbootshiro.util.ApplicationContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.List;

/**
 * Created by YangGang on 2021/12/14 18:10。
 */
@Slf4j
public class CustomRealm extends AuthorizingRealm {

    //获取授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.debug("进入获取授权方法 doGetAuthorizationInfo >>> ");
        //获取主要身份
        String principal = (String) principalCollection.getPrimaryPrincipal();
        //通过省份获取用户的角色和权限
        if (!ObjectUtils.isEmpty(principal)) {
            UserService userService = ApplicationContextUtil.getBeanByClass(UserService.class);
            //角色列表
            List<Role> roleList = userService.findUserRolesByUsername(principal);
            //权限列表
            List<Permission> permissionList = userService.findUserPermissionsByUsername(principal);
            log.debug("roleList :" + roleList.size());
            log.debug("permissionList :" + permissionList.size());
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            roleList.forEach(r -> info.addRole(r.getRoleTag()));
            permissionList.forEach(p -> info.addStringPermission(p.getPermissionTag()));
            return info;
        }
        return null;
    }

    //获取身份
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.debug("进入获取身份方法 doGetAuthenticationInfo >>> ");
        //获取身份
        String principal = (String) authenticationToken.getPrincipal();
        //数据库查询身份信息
        if (!ObjectUtils.isEmpty(principal)) {
            UserService userService = ApplicationContextUtil.getBeanByClass(UserService.class);
            User user = userService.findUserByUsername(principal);
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                    user.getUsername(), user.getPassword(), ByteSource.Util.bytes(user.getSalt()), this.getName());
            log.debug("user >>> " + user.toString());
            return simpleAuthenticationInfo;
        }
        return null;
    }

}
